import React from 'react';
import { Modal, Form, Input, message } from 'antd';

import { FormInstance } from 'antd/lib/form';
import { NumPropInfo } from '../../../../schema/NumProp';
import { createNumProp, modifyNumProp } from '../../../../servers/servers';
import { checkStr, verifyNull } from '../../../../../utils/tools';
const { TextArea } = Input;

/**
 * 号码属性props
 */
interface IProps {
  /**提交函数结束后的回调,编辑需要传obj，判断是否跳第一页 */
  callback: (obj?: any) => any;
}

/**
 * 号码属性state
 */
interface IState {
  // 当前的操作类型为新增还是编辑
  mode: 'create' | 'modify';
  // 当前操作弹出弹窗的可见性
  visible: boolean;
}

/**
 * 号码属性管理操作
 */
export class NumPropPop extends React.Component<IProps, IState> {
  // 表单引用
  private formRef: React.RefObject<FormInstance>;

  // 当前的号码属性信息
  private NumPropInfo?: NumPropInfo;

  constructor(props: IProps) {
    super(props);
    this.formRef = React.createRef<FormInstance>();
    this.state = {
      ...props,
      mode: 'create',
      visible: false,
    };
  }

  /**
   * 展开弹窗并设置类型
   */
  public open(mode: 'create' | 'modify'): void {
    this.setState({
      visible: true,
      mode: mode,
    });
  }

  /**
   * 关闭弹窗
   */
  public close(): void {
    this.formRef.current?.resetFields();
    this.setState({
      visible: false,
    });
  }

  /**
   * 设置表单值
   */
  public setValue(val: NumPropInfo) {
    setTimeout(() => {
      this.NumPropInfo = val;
      this.formRef.current?.setFieldsValue(val);
    }, 0);
  }

  /**
   * 提交 新增/编辑 的数据
   */
  private submitData(): void {
    const form = this.formRef.current;
    form?.validateFields().then(res => {
      const val = form.getFieldsValue() as NumPropInfo;
      if (this.state.mode === 'create') {
        createNumProp(val)
          .then(res => {
            if (res.code === 0) {
              message.success('创建成功');
              this.close();
              this.props.callback();
            }
          })
          .catch(error => {
            console.error(`系统异常: ${JSON.stringify(error)}`);
          });
      } else {
        const attributeId = this.NumPropInfo?.attributeId as number;
        modifyNumProp(attributeId, val)
          .then(res => {
            if (res.code === 0) {
              message.success('修改成功');
              this.close();
              this.props.callback(attributeId);
            }
          })
          .catch(error => {
            console.error(`系统异常: ${JSON.stringify(error)}`);
          });
      }
    });
  }

  render() {
    const { visible, mode } = this.state;

    const layout = {
      labelCol: { span: 6 },
      wrapperCol: { span: 16 },
    };
    const validateStr = (_: any, value: string) => {
      return checkStr(value) ? Promise.resolve() : Promise.reject('请输入英文数字下划线');
    };
    return (
      <>
        <Modal
          title={mode === 'create' ? '新建属性' : '编辑属性'}
          width={500}
          visible={visible}
          onOk={() => {
            this.submitData();
          }}
          onCancel={() => {
            this.close();
          }}
        >
          <Form {...layout} layout="horizontal" ref={this.formRef}>
            <Form.Item
              label="属性名称"
              name="attributeName"
              rules={verifyNull('请输入属性名称')}
              getValueFromEvent={event => {
                return event.target.value.replace(/\s+/g, '');
              }}
            >
              <Input maxLength={15} placeholder="请输入属性名称" />
            </Form.Item>
            <Form.Item
              label="属性助记符"
              name="attributeMnemonic"
              rules={[
                { required: true, message: '请输入属性助记符' },
                {
                  validator: validateStr,
                },
              ]}
              getValueFromEvent={event => {
                return event.target.value.replace(/\s+/g, '');
              }}
            >
              <Input maxLength={15} placeholder="请输入15位以内字母、数字和下划线组合" />
            </Form.Item>
            <Form.Item label="描述" name="attributeDesc">
              <TextArea rows={4} placeholder="请输入描述" maxLength={100} />
            </Form.Item>
          </Form>
        </Modal>
      </>
    );
  }
}
